<!-- 采购管理-基础设置-供应商类别设置 -->
<template>
  <div class="category-supplier">
    <PageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
      <template #buts>
        <a-button type="primary" @click="save">保存</a-button>
        <a-button @click="cancel">取消</a-button>
      </template>
    </PageHeader>
    <LevelSetting
      ref="levelSettingRef"
      :setting-info="info.list"
      :type="info.type"
    >
      <template #btn>
        <a-button
          :style="{
            marginTop: '20px',
          }"
          type="primary"
          @click="add"
          >新建类别</a-button
        >
        <a-button
          :style="{
            marginTop: '20px',
            marginLeft: '20px',
          }"
          type="primary"
          @click="edit"
          >点击编辑</a-button
        >
      </template>
      <template #default>
        <div
          class="content-box"
          v-for="(main, outerIndex) in info.list"
          :key="outerIndex"
        >
          <div>
            <div class="line"></div>
            <div class="content">
              <div class="main">
                <a-input
                  :disabled="!isEdit"
                  placeholder="请输入"
                  size="large"
                  allow-clear
                  v-model="main.details"
                >
                  <template #prepend> 类别</template>
                </a-input>
              </div>
              <div class="icon-box" v-if="isEdit">
                <a-popconfirm
                  content="是否要删除?"
                  @ok="deleteItem(main, outerIndex)"
                >
                  <icon-delete
                    :size="16"
                    :style="{
                      color: 'red',
                    }"
                    class="icon"
                  />
                </a-popconfirm>
              </div>

              <div class="sub">
                <div
                  :style="{
                    display: 'flex',
                    marginBottom: '20px',
                  }"
                  v-for="(sub, innerIndex) in main.child"
                  :key="innerIndex"
                >
                  <div>
                    <a-space>
                      <a-input
                        :disabled="!isEdit"
                        placeholder="请输入"
                        size="large"
                        allow-clear
                        v-model="sub.details"
                      >
                        <template #prepend> 子类别 </template>
                      </a-input>

                      <div class="icon-box" style="margin-top: 20px">
                        <icon-plus
                          class="icon"
                          :size="16"
                          :style="{
                            color: '#4e7cf7',
                          }"
                          @click="addItem(outerIndex, innerIndex)"
                          v-if="isEdit"
                        />
                        <a-popconfirm
                          v-if="isEdit"
                          content="是否要删除?"
                          @ok="deleteSonItem(sub.id, outerIndex, innerIndex)"
                        >
                          <icon-delete
                            :size="16"
                            :style="{
                              color: 'red',
                            }"
                            class="icon"
                          />
                        </a-popconfirm>
                      </div>
                    </a-space>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </LevelSetting>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import cloneDeep from 'lodash.clonedeep';
  import dayjs from 'dayjs';
  import {
    GetSupplierCategoryInfo,
    PostSupplierCategoryInfo,
    deleteSupplierCategory,
  } from '@/api/buy-management/supplier-management/base-setting';

  const router = useRouter();
  const title: string = '供应商类别设置';
  // let msg = dayjs(new Date()).format('YYYY-MM-DDTHH:mm:ssZ');

  const breadCrumb: string[] = [
    '采购管理',
    '供应商管理',
    '供应商设置',
    '供应商类别设置',
  ];

  const info: any = reactive({
    list: [],
    type: 4,
  });

  let levelSettingRef = ref(); // 储存组件的ref

  // const tree = (data?: any) => {
  //   data.forEach((item: any) => {
  //     item.show = true;
  //     if (item.child) {
  //       tree(item.child);
  //     }
  //   });
  //   return data;
  // };

  const getData = async () => {
    try {
      const { data, type } = await GetSupplierCategoryInfo();
      // info.list = tree(data);
      info.list = data;
      info.list.forEach((item) => {
        item.child = item.child || [{ pid: item.id }];
      });
      info.type = type;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  getData();

  // 新增一项
  const add = () => {
    const item = {
      details: '',
      child: [
        {
          details: '',
          show: true,
        },
      ],
    };
    info.list.push(item);
  };

  let isEdit = ref(false); // 判断用户是否点击编辑按钮

  //编辑
  const edit = () => {
    isEdit.value = !isEdit.value;
  };

  /*
    删除一项
    根据type来删除，
    first： 删除主类别
    second： 删除子类别
  */
  const ids: any = ref([]);
  const deleteItem = async (val: any, outerIndex: number) => {
    if (val.id) ids.value.push(val.id);
    info.list.splice(outerIndex, 1);
  };

  // 增加一个子类别
  const addItem = (outerIndex: number, innerIndex: number) => {
    let item = {
      details: '',
      show: true,
    };
    info.list[outerIndex].child.splice(innerIndex + 1, 0, item);
  };

  const deleteSonItem = (
    id: number,
    outerIndex: number,
    innerIndex: number
  ) => {
    if (id) ids.value.push(id);
    info.list[outerIndex].child.splice(innerIndex, 1);
  };

  // 保存
  const save = async () => {
    try {
      const data: any = [];
      const deleteArr: any = cloneDeep(ids.value);
      info.list.forEach((element: any, index: number) => {
        // data[index].details = element.details;
        if (element.show) {
          data.push({
            name: element.name,
            details: element.details,
            child: [],
            pid: element.pid,
            type: element.type,
            deletedAt: element.deletedAt,
            id: element.id,
          });
        } else {
          data.push({
            name: element.name,
            details: element.details,
            child: [],
            pid: element.pid,
            type: element.type,
            id: element.id,
          });
        }
        element.child = element.child ? element.child : [];
        element.child.forEach((child: any) => {
          if (child.show) {
            data[index].child.push({
              name: child.name,
              details: child.details,
              pid: child.pid,
              type: child.type,
              id: child.id,
              deletedAt: child.deletedAt,
            });
          } else {
            data[index].child.push({
              name: child.name,
              details: child.details,
              pid: child.pid,
              type: child.type,
              id: child.id,
            });
          }
        });
      });

      await PostSupplierCategoryInfo({
        data,
      });
      await deleteSupplierCategory({
        ids: deleteArr,
      });
      // router.go(0);
      getData();
      isEdit.value = false;
    } catch (err: unknown) {
      console.log(err);
    }
  };

  // 取消按钮
  const cancel = () => {
    router.back();
  };
</script>

<style scoped lang="less">
  .category-supplier {
    .content-box {
      margin-top: 20px;
      .line {
        width: 100%;
        height: 10px;
        background-color: #f5f7fa;
        margin-bottom: 20px;
      }
      .content {
        display: flex;
        // flex-wrap: wrap;
        .main {
          flex: 1;
        }
        .icon-box {
          width: 80px;
          .icon {
            cursor: pointer;
            position: relative;
            top: 18px;
            transform: translateY(-50%);
            margin-left: 10px;
          }
        }

        .sub {
          flex: 1;
          margin-left: 20px;

          .icon-box {
            width: 80px;
            .icon {
              cursor: pointer;
              position: relative;
              top: 50%;
              transform: translateY(-50%);
              margin-left: 10px;
            }
          }
        }
      }
    }
  }
</style>
